package com.winit.issue.repository;

import com.winit.issue.model.IssueRelation;
import com.winit.issue.model.IssueRelationId;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import javax.transaction.Transactional;
import java.util.List;

public interface IssueRelationRepository extends CrudRepository<IssueRelation, IssueRelationId> {
    List<IssueRelation> findByIssueId(String issueId);

    @Transactional
    int deleteByRelationIdAndType(String relationId, String type);

    @Query(value = "SELECT DISTINCT (issue_id) FROM matrix_issue_relation WHERE relation_id = ?1 AND type = ?2", nativeQuery = true)
    List<String> getAllIssueIdsByRelationIdAndType(String relationId, String type);

    @Query(value = "SELECT COUNT(1) FROM matrix_issue_relation mir, matrix_requirements mr WHERE mir.relation_id = mr.req_id AND mir.issue_id = ?1 AND mr.req_status != 'COMPLETED' AND mr.req_is_del != 0", nativeQuery = true)
    int countUnfinishedReqOfIssue(String issueId);


    @Query(value = "SELECT COUNT(1) FROM matrix_issue_relation WHERE issue_id = ?1 AND type = 'REQ'", nativeQuery = true)
    int countIssueReq(String issueId);
}
